<template>
    <div class="box-content">
        <div class="navigation">内容管理/课程内容</div>
        <!--搜索-->
        <div class="mt-3">
            <div>
                <el-input type="text" style="width: 200px;"  :clearable="true" class=" mrt-10" v-model="search.inputName" placeholder="输入关键字课程内容"></el-input>
                <el-button type="primary" class=" mrt-10" @click="onSearch">查询</el-button>
                <el-button type="primary" @click="openShanHu">新增</el-button>
            </div>
        </div>
        <!--表格-->
        <div class="mt-3">
            <el-table
                    :data="userData"
                    v-loading="loading"
                    align="center"
                    :element-loading-text="loadText"
                    :header-cell-style="tableHeaderColor"
                    stripe
                    style="width: 100%">
                <el-table-column
                        prop="id"
                        align="center"
                        label="编号"
                        width="100"
                >
                </el-table-column>
                <el-table-column
                        prop="title"
                        align="center"
                        label="标题"
                >
                </el-table-column>
                <el-table-column
                        prop="brief_info"
                        align="center"
                        label="简介"
                >
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="conten_url"
                        label="封面图"
                >
                    <template slot-scope="scope">
                        <div align="center"><img :src="scope.row['conten_url']" alt="" style="height: 50px;"></div>
                    </template>
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="video_url"
                        label="视频路径"
                >
                </el-table-column>
                <el-table-column
                        label="详情"
                >
                    <template slot-scope="scope">
                        <div style="width: 200px;overflow:hidden;text-overflow:ellipsis;white-space: nowrap;">{{scope.row['details']}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="level1_link.title"
                        align="center"
                        label="专业"
                >
                </el-table-column>
                <el-table-column
                        prop="level2_link.title"
                        align="center"
                        label="分类"
                >
                </el-table-column>
                <el-table-column
                        align="center"
                        label="是否推荐"
                >
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.recommend"
                                :active-value="1"
                                :inactive-value="0"
                                @change=changeRecommend(scope.row)></el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="user_count"
                        align="center"
                        label="报名人数"
                >
                    <!--<template slot-scope="scope">-->
                        <!--<el-switch-->
                                <!--v-model="scope.row.chosed"-->
                                <!--:active-value="1"-->
                                <!--:inactive-value="0"-->
                                <!--@change=changeChosed(scope.row)></el-switch>-->
                    <!--</template>-->
                </el-table-column>
                <el-table-column
                        label="创建日期"
                        align="center"
                        width="100">
                    <template slot-scope="scope">
                        <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(0, 11):'无'}}</div>
                        <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(11 ):'无'}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="状态/操作"
                        align="center"
                        fixed="right"
                        width="220"
                >
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="primary"
                                @click="handleEdit(scope.row)">编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="mt-3 float-right">
                <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageInfo.current_page"
                        :page-size="pageInfo.per_page"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pageInfo.total">
                </el-pagination>
            </div>
        </div>
        <!--新增对话框-->
        <el-dialog :title="dialog.title"
                   top="2vh"
                   :visible.sync="dialogFormVisible"
                   :close-on-click-modal="false"
                   width="1000px">
            <el-form :model="form" :rules="rules" ref="form" label-width="70px" v-loading="loadingDialig"  element-loading-text="拼命上传中，请稍等。。。">

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="封面图" prop="conten_url">
                            <el-upload
                                    class="avatar-uploader"
                                    action="123"
                                    :show-file-list="false"
                                    :before-upload="beforeAvatarUpload">
                                <img v-if="form.conten_url" :src="form.conten_url" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="视频" prop="video_url">
                            <!--<el-upload-->
                                    <!--class="avatar-uploader"-->
                                    <!--action="123"-->
                                    <!--:show-file-list="false"-->
                                    <!--:before-upload="beforeAvatarUploads">-->
                                <!--<video v-if="form.video_url" :src="form.video_url" style="width:100px ;height: 100px;" controls="controls">-->
                                    <!--您的浏览器不支持 video 标签。-->
                                <!--</video>-->
                                <!--<i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
                            <!--</el-upload>-->
                            <!-- action必选参数, 上传的地址 -->
                            <el-upload class="avatar-uploader el-upload--text"
                                       :action="$store.state.uploadUrl"
                                       :show-file-list="false"
                                       :on-success="handleVideoSuccess"
                                       :before-upload="beforeUploadVideo"
                                       :on-progress="uploadVideoProcess">
                                <video v-if="form.video_url !='' && videoFlag == false" :src="form.video_url" class="avatar" controls="controls">您的浏览器不支持视频播放</video>
                                <i v-else-if="form.video_url =='' && videoFlag == false" class="el-icon-plus avatar-uploader-icon"></i>
                                <el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent"></el-progress>
                            </el-upload>
                            <P class="text">请保证视频格式正确，且不超过10M</P>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="是否推荐" prop="recommend">
                            <el-radio-group v-model="form.recommend">
                                <el-radio :label="1">是</el-radio>
                                <el-radio :label="0">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!--<el-form-item label="是否首页" prop="chosed">-->
                            <!--<el-radio-group v-model="form.chosed">-->
                                <!--<el-radio :label="1">是</el-radio>-->
                                <!--<el-radio :label="0">否</el-radio>-->
                            <!--</el-radio-group>-->
                        <!--</el-form-item>-->
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="专业" prop="level1">
                            <el-select v-model="form.level1" placeholder="请选择专业">
                                <el-option
                                        v-for="item in typeData1"
                                        :key="item.id"
                                        :label="item.title"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="分类" prop="level2">
                            <el-select v-model="form.level2" placeholder="请选择分类">
                                <el-option
                                        v-for="item in typeData2"
                                        :key="item.id"
                                        :label="item.title"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入标题" ></el-input>
                </el-form-item>
                <el-form-item label="课时" prop="time_count">
                    <el-input type="number" v-model="form.time_count" placeholder="请输入课时" ></el-input>
                </el-form-item>
                <el-form-item label="简介" prop="brief_info">
                    <el-input type="textarea" rows="3" v-model="form.brief_info" placeholder="请输入简介" ></el-input>
                </el-form-item>
                <el-form-item label="详情" prop="details"  style="height: 510px;">
                    <quill-editor
                            style="height:450px;"
                            v-model="form.details"
                            ref="myQuillEditor"
                            :options="editorOption"
                            @change="onEditorChange($event)">
                    </quill-editor>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" v-if="!dialog.isEdit" :loading="loadingCreate" @click="submitCostomer('form')">{{loadingCreate?'创建中':'点击创建'}}</el-button>
                <el-button type="primary" v-if="dialog.isEdit"  :loading="loadingCreate" @click="submitCostomer('form')">{{loadingCreate?'修改中':'点击修改'}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { quillEditor } from 'vue-quill-editor';
    import axios from 'axios';
    export default {
        name: "userList",
        data() {
            var validateName = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入文件类型'));
                }else{
                    callback();
                }
            };
            return {
                editorOption:{},
                editId: null,
                userInfo: {},
                pageInfo: {
                    per_page: 10,
                    total: 0,
                    current_page: 1
                },
                loadText: '数据加载中',
                userData: [],
                searchStr:'',
                search: {
                    roleStatus:'',
                    inputName:''
                },
                baseId: null,
                loading: false,
                loadingDialig: false,
                loadingCreate: false,
                dialogFormVisible: false,
                api:'api/admin/express/course',
                form: {
                    title:'',
                    brief_info: '',
                    time_count: '',
                    conten_url: '',
                    video_url: '',
                    details:'',
                    recommend:1,
                    chosed:1,
                    level1:'',
                    level2:''
                },
                videoFlag:false,
                videoUploadPercent:'',
                dialog: {
                    title: '',
                    isEdit: false
                },
                typeData1:[],
                typeData2:[],
                rules: {
                    title: [
                        {validator: validateName, trigger: 'change'}
                    ],
                    imageUrl: [
                        {required: true, message: '请上传icon', trigger: 'change'}
                    ],
                    level1: [
                        {required: true, message: '请选择专业', trigger: 'change'}
                    ],
                    level2: [
                        {required: true, message: '请选择分类', trigger: 'change'}
                    ]
                }

            }
        },
        watch: {
            dialogFormVisible:function (val) {
                if (!val) {
                    Object.keys(this.form).forEach(key => this.form[key] = '');
                    this.$refs['form'].resetFields();
                    this.editId = null;
                }
            }
        },
        created() {
            this.getType1List();
            this.getType2List();
            this.getContentList();
        },
        methods: {

            beforeUploadVideo(file) {
                const isLt10M = file.size / 1024 / 1024  < 10;
                if (['video/mp4', 'video/ogg', 'video/flv','video/avi','video/wmv','video/rmvb'].indexOf(file.type) == -1) {
                    this.$message.error('请上传正确的视频格式');
                    return false;
                }
                if (!isLt10M) {
                    this.$message.error('上传视频大小不能超过10MB哦!');
                    return false;
                }
            },
            uploadVideoProcess(event, file, fileList){
                this.videoFlag = true;
                this.videoUploadPercent = Number(file.percentage.toFixed(0));
            },
            handleVideoSuccess(res, file) {                               //获取上传图片地址
                this.videoFlag = false;
                this.videoUploadPercent = 0;
                if(res.code == 200){
                    // this.form.videoUploadId = res.data.uploadId;
                    this.form.video_url = res.data.path;
                }else{
                    this.$message.error('视频上传失败，请重新上传！');
                }
            },
            getType1List() {
                this.$http.get('api/admin/common/courseType?level=1')
                    .then((result) => {
                        this.typeData1 = result.data;
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            getType2List() {
                this.$http.get('api/admin/common/courseType?level=2')
                    .then((result) => {
                        this.typeData2 = result.data;
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            onEditorChange(val){//内容改变事件
                // console.info('内容改变事件',val);
                this.form.details = val.html;
            },
            beforeAvatarUpload (file) {
                var fileName=new Array();
                fileName =file.name.split('.');
                const extension = fileName[fileName.length-1] === 'jpg'
                const extension2 =  fileName[fileName.length-1]=== 'png'
                if (!extension && !extension2) {
                    this.$message({
                        message: '上传模板只能是jpg、png格式!',
                        type: 'warning'
                    });
                }
                if (extension || extension2) {
                    let fd = new FormData();
                    fd.append('fileUpload', file);
                    this.newImport(fd);
                }
                return false;
            },
            beforeAvatarUploads (file) {
                // if (extension || extension2) {
                    let fd = new FormData();
                    fd.append('fileUpload', file);
                    this.newImports(fd);
                // }
                return false;
            },
            newImports (data) {
                let config = {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Authorization' : 'Bearer' + localStorage.getItem('token')
                    }
                };
                this.loadingDialig = true;
                axios.post(process.env.VUE_APP_API_HOST + 'api/admin/common/uploadInfo', data,config)
                    .then((res) => {
                        this.form.video_url = res.data.data.path;
                        this.loadingDialig = false;
                    })
                    .catch((err) => {
                        this.loadingDialig = false;
                        this.$message.warning(err.response.data.msg || "数据异常，请重试");
                    })
            },
            newImport (data) {
                let config = {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Authorization' : 'Bearer' + localStorage.getItem('token')
                    }
                };
                this.loadingDialig = true;
                axios.post(process.env.VUE_APP_API_HOST + 'api/admin/common/uploadInfo', data,config)
                    .then((res) => {
                        this.form.conten_url = res.data.data.path;
                        this.loadingDialig = false;
                    })
                    .catch((err) => {
                        this.loadingDialig = false;
                        this.$message.warning(err.response.data.msg || "数据异常，请重试");
                    })
            },
            changeRecommend(val) {
                let params = {
                    recommend: val.recommend
                };
                this.$http.put(this.api+'/' + val.id, params)
                    .then((result) => {
                        this.$message({
                            type: 'success',
                            message: result.msg,
                            during: 1000
                        });
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },

            changeName(val) {
                this.search.inputName = val;
            },
            openShanHu(){
                this.dialog.title = '添加课程内容';
                this.dialog.isEdit = false;
                this.dialogFormVisible = true;
            },
            getContentList() {
                this.loading = true;
                this.$http.get(this.api + this.searchStr, {
                    params: {
                        pageSize: this.pageInfo.per_page,
                        page: this.pageInfo.current_page
                    }
                })
                    .then((result) => {
                        this.userData = result.data;
                        this.pageInfo.total = result.meta.total;
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            onSearch() {
                this.searchStr ="";
                if (this.search.inputName) {
                    this.addConStr();
                    this.searchStr += `title$=%${this.search.inputName}%`;
                }
                this.pageInfo.current_page = 1;
                this.getContentList();
            },
            addConStr() {
                if (this.searchStr.length > 0) {
                    this.searchStr += '&';
                } else {
                    this.searchStr += '?';
                }
            },
            submitCostomer(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.creatShanHu();
                    } else {
                        return false;
                    }
                });
            },
            creatShanHu(){
                this.loadingCreate = true;
                let params;
                if (this.dialog.isEdit) {
                    params={
                        title: this.form.title,
                        time_count:this.form.time_count,
                        conten_url:this.form.conten_url,
                        details:this.form.details,
                        recommend:this.form.recommend,
                        // chosed:this.form.chosed,
                        video_url:this.form.video_url,
                        level1:this.form.level1,
                        level2:this.form.level2,
                        brief_info:this.form.brief_info
                    };
                    this.$http.put(this.api + '/' + this.baseId, params)
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '修改成功!',
                                during:1000
                            });
                            this.dialogFormVisible = false;
                            this.loadingCreate = false;
                            this.getContentList();
                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                } else {
                    params={
                        title: this.form.title,
                        time_count:this.form.time_count,
                        conten_url:this.form.conten_url,
                        details:this.form.details,
                        recommend:this.form.recommend,
                        // chosed:this.form.chosed,
                        video_url:this.form.video_url,
                        level1:this.form.level1,
                        level2:this.form.level2,
                        brief_info:this.form.brief_info
                    };
                    this.$http.post(this.api, params)
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '添加成功!',
                                during:1000
                            });
                            this.dialogFormVisible = false;
                            this.loadingCreate = false;
                            this.getContentList();
                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }

            },
            handleEdit(val) {
                this.baseId = val.id;
                this.dialog.title = '编辑课程内容';
                this.dialog.isEdit = true;
                this.dialogFormVisible = true;
                this.loadingDialig = true;
                this.$http.get(this.api + '/' + val.id)
                    .then((result) => {
                        this.editId = result.data.id;
                        this.form.title = result.data.title;
                        this.form.content = result.data.content;
                        this.form.time_count = result.data.time_count;
                        this.form.conten_url = result.data.conten_url;
                        this.form.recommend = result.data.recommend;
                        // this.form.chosed = result.data.chosed;
                        this.form.brief_info = result.data.brief_info;
                        this.form.video_url = result.data.video_url;
                        this.form.level1 = result.data.level1;
                        this.form.level2 = result.data.level2;
                        this.form.details = result.data.details;
                        this.loadingDialig = false;
                    })
                    .catch((err) => {
                        this.loadingDialig = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleDelete(val) {
                this.$confirm('此操作将永久删除课程内容, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete(this.api+'/' + val.id)
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '课程内容删除成功!',
                                during:1000
                            });
                            this.getContentList();
                        })
                        .catch((err) => {
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }).catch(() => {
                });
            },
            handleSizeChange(val) {
                this.pageInfo.current_page = 1;
                this.pageInfo.per_page = val;
                this.getContentList();
            },
            handleCurrentChange(val) {
                this.pageInfo.current_page = val;
                this.getContentList();
            },
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            }
        }
    }
</script>

<style lang="less">
    .check-children{
        cursor: pointer;
    }
    .check-children:hover{
        color: #409EFF;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
    }
    .avatar {
        width: 100px;
        height: 100px;
        display: block;
    }
</style>